package com.soft.zzti.service.impl;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.soft.zzti.dao.StaffDao;
import com.soft.zzti.dao.UserDao;
import com.soft.zzti.entity.TPassword;
import com.soft.zzti.entity.TStaffBean;
import com.soft.zzti.service.StaffService;
import com.soft.zzti.util.MD5Util;

@Service("staffService")
public class StaffServiceImpl implements StaffService {
	@Resource
	private StaffDao staffDao;
	@Resource
	private UserDao userDao;

	@Override
	public List<Integer> findStaffRightByStaffID(String staffID) throws Exception{
		// TODO Auto-generated method stub
		List<Integer> staffRightLists = staffDao.queryStaffRight(staffID);
		return staffRightLists;
	}

	@Override
	public int updateStaffInfo(TStaffBean staffInfo) throws Exception {
		// TODO Auto-generated method stub
		return staffDao.updateStaffInfo(staffInfo);
	}

	@Override
	public PageInfo<TStaffBean> getAllStaffInfo(TStaffBean staff, Integer pageNo, Integer pageSize) throws Exception {
		// TODO Auto-generated method stub
		PageHelper.startPage(pageNo, pageSize);
		List<TStaffBean> list = staffDao.selectAll(staff);
		PageInfo<TStaffBean> page = new PageInfo<TStaffBean>(list);
		return page;
	}

	@Override
	public int deleteStaff(String staffId) throws Exception {
		// TODO Auto-generated method stub
		int result = staffDao.deleteByPrimaryKey(staffId);
		return result;
	}

	@Override
	public TStaffBean getStaffByStaffId(String staffId) throws Exception {
		// TODO Auto-generated method stub
		return staffDao.queryStaffInfo(staffId);
	}

	@Transactional
	@Override
	public int addStaff(TStaffBean staffInfo,String password,JSONObject userSession) throws Exception {
		/*
		 *  此操作为部门管理员新注册本部门的员工，
		 *  departID，higherupID为从部门管理员的session中获取
		 *  roleID 自己手动赋值为3 
		 */
		int departID = (int) userSession.get("departID");
		String higherupID = (String) userSession.get("managerID");
		staffInfo.setDepartID(departID);
		staffInfo.setHigherupID(higherupID);
		staffInfo.setRoleID(3);
		int addStaffResult = staffDao.insertSelective(staffInfo);
		
		
		//t_staff表中数据insert成功后，往t_password添加数据
		TPassword record = new TPassword();
		record.setAuto_id(0);
		record.setContact_phone(staffInfo.getContactPhone());
		record.setRole_id(3);
		record.setUser_id(staffInfo.getStaffID());
		record.setUser_name(staffInfo.getStaffName());
		//Md5加密处理
		System.out.println("md5 加密前-"+password);
		password = MD5Util.MD5(password);
		System.out.println("md5 加密后-"+password);
		record.setUser_password(password);
		int pResult = userDao.insertSelective(record);
		
		return pResult+addStaffResult;
	}

}
